// 定义用户相关的仓库
import {defineStore} from 'pinia'
import {reqCode,reqUserLogin} from '@/api/hospital/index'
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";

const useUserStore = defineStore('User',{
    state:()=>{
        return{
            visiable:(false as any),  //用于控制登录组件dialog显示与隐藏
            code:('' as any),  //用于存储用户验证码
            userInfo: JSON.parse(GET_TOKEN() as string) || {}
        }
    },
    actions:{
        // 获取验证码的方法
        async getCode(phone:any){
            let result = await reqCode(phone)
            if(result.code==200){
               this.code=result.data
               return 'ok'
            } else{
                return Promise.reject(new Error(result.message))
            }
        },
        // 用户登录的方法
        async userLogin(loginParam:any){
            let result = await reqUserLogin(loginParam)
            if(result.code==200){
                this.userInfo = result.data
                // 本地存储持久化存储用户信息
               SET_TOKEN(JSON.stringify(this.userInfo))
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        // 退出登陆 
        logout(){
            this.userInfo = {},
            REMOVE_TOKEN()
        },
        //查询微信扫码的接口(看本地存储是否存储数据)
        queryState() {
            //开启定时器每隔一段时间问:本地村是都拥有用户信息
            let timer = setInterval(() => {
                //本地存储已有有数据:扫码成功
                if (GET_TOKEN()) {
                    //关闭对话框
                    this.visiable = false;
                    this.userInfo = JSON.parse(GET_TOKEN() as string);
                    clearInterval(timer);
                }
            }, 1000);
        }
    },
    getters:{}
})

export default useUserStore